﻿using Common;

namespace yongGu
{
    public class PushStockInTask
    {
        public void GetStockInFromErp()
        {
            while (true)
            {
                try
                {
                    Config.Logger.Information("入库任务开始记录");
                    DataAccess ds = new DataAccess();
                    var stockIn = ds.GetStockIn();
                    var c = Convert(stockIn);
                    foreach (var r in c)
                    {
                        PostToHY(r);
                    }
                    if(c.Count>0)
                        Config.Logger.Information("成功出库{0}笔记录", c.Count);

                }
                catch (Exception ex)
                {
                    Config.Logger.Error(ex.StackTrace +"\r\n"+ ex.Message);
                }
                finally 
                {
                    Config.Logger.Information("入库睡眠30s");
                    Thread.Sleep(30 * 1000);
                }
            }
        }
        private List<RecordInModel> Convert(List<StockInModel> stock)
        {
            List<RecordInModel> result = new List<RecordInModel>();
            foreach (var item in stock)
            {
                var record = new RecordInModel();
                record.RecordId = item.FEntryId;
                record.ksBinCode = item.StockLoc;
                record._type = item.Type;
                record.orderNo = item.FBillNo + "_" + item.FSeq;
                record.moveInOrderBinDetailDTOS = [new RecordInDetailModel()
                {
                    qtyRestocked = System.Convert.ToInt32(item.FRealQty),
                    skuCode = item.FNumber,
                    skuName = item.FName
                }];
                result.Add(record);

            }
            return result;
        }
        private void PostToHY(RecordInModel recordmodel)
        {
            HttpHelper httpHelper = new HttpHelper();
            DataAccess ds = new DataAccess();
            try
            {
                var r = httpHelper.Post<ResponseFromWMS, RecordInModel>(Config.WMS_URL + "/adapter/api/haiq?api=HAIQ_WMS_RECEIPT_CREATE", recordmodel);
                Console.WriteLine(r.code);
                ds.SetInResult(recordmodel.RecordId,  r.message, recordmodel._type);
            }
            catch(Exception ex)
            {
                ds.SetInResult(recordmodel.RecordId, ex.Message, recordmodel._type);
            }
        }
    }
}
